package com.financing.platform.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;


/**
 * 短信发送
 * @author ios
 *
 */
public class SMSSend {

	private static String urlString="http://esms9.10690007.net/sms/mt";


	/**
	 * 响应action
	 */
	private static String command = "MULTI_MT_REQUEST";
	/**
	 * 用户账号
	 */
	private static String spid = "9218";
	/**
	 * 认证密钥
	 */
	private static String sppassword="fupG1Znm";

	private static String dc = "15";

	/**
	 * 服务代码
	 */
	private static String spsc = "03";

	private static SMSSend client = null;
	public SMSSend(){
		
	}
	public synchronized static SMSSend getSMSSend(){
		if(client==null){
			try {
				client=new SMSSend();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return client;
	}
	public static void main(String[] args) throws Exception {
		List list = new ArrayList<String>();
		list.add("18321248185");
		System.out.println(new SMSSend().sendSMS(list, "您的认证资料已通过审核，现在可以登录金策师App定制您的店铺了！"));
	}

	/**
	 *
	* @Title: sendSMS
	* @Description:  短信下发接口  直接传入手机号和内容就能直接下发
	* @param   mobileList  手机号
	* @param   content   短信内容
	* @param @throws Exception
	* @return Map<String,Object>
	* @throws
	 */
	public Map<String,Object> sendSMS(List<String> mobileList,String content) throws Exception{

		Map<String,String> params = new HashMap<String, String>();
		StringBuffer mobiles = new StringBuffer();
		for(String mobile : mobileList){
			mobiles.append("86"+mobile);
			mobiles.append(",");
		}
		String mobilesStr = mobiles.toString();
		mobilesStr = mobilesStr.substring(0,mobilesStr.length()-1);
		params.put(MlinkDict.command, command);
		params.put(MlinkDict.spid, spid);
		params.put(MlinkDict.sppassword,sppassword);
		params.put(MlinkDict.dc, dc);
		params.put(MlinkDict.das, mobilesStr);
		params.put(MlinkDict.spsc, spsc);
		params.put(MlinkDict.sm, encodeHexStr(15,content));

		return  request(params);

	}

	/**
	 * 请求短信供应商
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private Map<String,Object> request(Map<String,String> params) throws Exception{
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = postForm(urlString, params);
		HttpResponse httpResponse = httpClient.execute(httpPost);
		InputStream is = httpResponse.getEntity().getContent();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer resultSringBuffer =new StringBuffer();
		String result = null;
		while((result = br.readLine())!=null){
			resultSringBuffer.append(result);
		}
		return StringPraser2Map(resultSringBuffer.toString());
	}

	/**
	 * 解析放回结果放map
	 * @param result 请求短信运营商后返回的结果
	 * @return
	 */
	private Map<String,Object> StringPraser2Map(String result){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(result != null && result.trim().length()>0){
			String[] strArray = result.split("&");
			for(String tmp : strArray){
				String[] keyValue = tmp.split("=");
				resultMap.put(keyValue[0], keyValue[1]);
			}
		}
		return resultMap;
	}

	/**
	 *
	* @Title: postForm
	* @Description: 封装httpPost
	* @param   url 请求地址
	* @param   params  请求参数
	* @param @throws Exception
	* @return HttpPost
	* @throws
	 */
	private HttpPost postForm(String url,Map<String,String> params) throws Exception{

		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> listNameValuePair = new ArrayList<NameValuePair>();

		for(String key : params.keySet()){
			listNameValuePair.add(new BasicNameValuePair(key,(String) params.get(key)));
		}

		httpPost.setEntity(new UrlEncodedFormEntity(listNameValuePair,HTTP.UTF_8));

		return httpPost;
	}

	/**
     * 将普通字符串转换成Hex编码字符串
     *
     * @param dataCoding 编码格式，15表示GBK编码，8表示UnicodeBigUnmarked编码，0表示ISO8859-1编码
     * @param realStr 普通字符串
     * @return Hex编码字符串
     * @throws UnsupportedEncodingException
     */
    public static String encodeHexStr(int dataCoding, String realStr) {
        String hexStr = null;
        if (realStr != null) {
            try {
                if (dataCoding == 15) {
                    hexStr = new String(Hex.encodeHex(realStr.getBytes("GBK")));
                } else if ((dataCoding & 0x0C) == 0x08) {
                    hexStr = new String(Hex.encodeHex(realStr.getBytes("UnicodeBigUnmarked")));
                } else {
                    hexStr = new String(Hex.encodeHex(realStr.getBytes("ISO8859-1")));
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println(e.toString());
            }
        }
        return hexStr;
    }
}
